package cn.dm.example.hystrix;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/hystrix1")
@DefaultProperties(defaultFallback = "defaultFail")
public class HystrixController1 {

    /**
     * 访问 http://localhost:8080/hystrix1/test1
     * 页面出现 fail1
     * 控制台出现如下日志信息
     * 2022-06-18 15:25:38.333  WARN 13668 --- [ixController1-1] c.dm.example.hystrix.HystrixController1  : fail1
     * <p>
     * 即访问原url时出现异常,服务降级到fail1
     * (一次服务降级)
     */
    @HystrixCommand(fallbackMethod = "fail1")
    @RequestMapping("/test1")
    public String test1() {
        throw new RuntimeException();
    }

    private String fail1() {
        log.warn("fail1");
        return "fail1";
    }

    /**
     * 访问 http://localhost:8080/hystrix1/test2
     * 页面出现 default fail
     * 控制台出现如下日志信息
     * 2022-06-18 15:28:10.959  WARN 13668 --- [ixController1-3] c.dm.example.hystrix.HystrixController1  : fail2
     * 2022-06-18 15:28:10.967  WARN 13668 --- [ixController1-4] c.dm.example.hystrix.HystrixController1  : fail3
     * 2022-06-18 15:28:10.967  WARN 13668 --- [ixController1-4] c.dm.example.hystrix.HystrixController1  : default fail
     * <p>
     * 即访问原url时出现异常,服务降级到fail2,fail2又出现异常降级到fail3,fail3出现异常降级到defaultFail
     * 见类最上面配置 @DefaultProperties(defaultFallback = "defaultFail")
     * (即多次服务降级)
     */
    @HystrixCommand(fallbackMethod = "fail2")
    @RequestMapping("/test2")
    public String test2() {
        throw new RuntimeException();
    }

    @HystrixCommand(fallbackMethod = "fail3")
    private String fail2() {
        log.warn("fail2");
        throw new RuntimeException();
    }

    @HystrixCommand
    private String fail3() {
        log.warn("fail3");
        throw new RuntimeException();
    }

    private String defaultFail() {
        log.warn("default fail");
        return "default fail";
    }
}
